package com.tca.common.core.utils;

import java.io.*;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Admin
 * @date 2019/2/26
 */
public class Base64Utils {

	private final static Logger logger = Logger.getLogger(Base64Utils.class.getName());

	private Base64Utils() { }

    private static final Pattern FILE_SUFFIX_PATTERN = Pattern.compile("data:(\\w*?)/(.*?);");
    static private final int BASE_LENGTH = 128;
    static private final int LOOK_UP_LENGTH = 64;
    static private final int TWENTY_FOUR_BIT_GROUP = 24;
    static private final int BIT_EIGHT = 8;
    static private final int BIT_SIXTEEN = 16;
    static private final int BIT_SIX = 6;
    static private final int BYTE_FOUR = 4;
    static private final int SIGN = -128;
    static private final char PAD = '=';
    static private final boolean F_DEBUG = false;
    static final private byte[] BASE_64_ALPHABET = new byte[BASE_LENGTH];
    static final private char[] LOOK_UP_BASE_64_ALPHABET = new char[LOOK_UP_LENGTH];

    static {

        for (int i = 0; i < BASE_LENGTH; ++i) {
            BASE_64_ALPHABET[i] = -1;
        }
        for (int i = 'Z'; i >= 'A'; i--) {
            BASE_64_ALPHABET[i] = (byte)(i - 'A');
        }
        for (int i = 'z'; i >= 'a'; i--) {
            BASE_64_ALPHABET[i] = (byte)(i - 'a' + 26);
        }

        for (int i = '9'; i >= '0'; i--) {
            BASE_64_ALPHABET[i] = (byte)(i - '0' + 52);
        }

        BASE_64_ALPHABET['+'] = 62;
        BASE_64_ALPHABET['/'] = 63;

        for (int i = 0; i <= 25; i++){
			LOOK_UP_BASE_64_ALPHABET[i] = (char)('A' + i);
		}
        for (int i = 26, j = 0; i <= 51; i++, j++){
			LOOK_UP_BASE_64_ALPHABET[i] = (char)('a' + j);
		}
        for (int i = 52, j = 0; i <= 61; i++, j++){
			LOOK_UP_BASE_64_ALPHABET[i] = (char)('0' + j);
		}
        LOOK_UP_BASE_64_ALPHABET[62] = (char)'+';
        LOOK_UP_BASE_64_ALPHABET[63] = (char)'/';

    }

    /**
     * 获取文件的大小
     *
     * @param inFile 文件
     * @return 文件的大小
     */
    public static int getFileSize(File inFile) {

        try (InputStream in = new FileInputStream(inFile)) {
            // 文件长度
            int len = in.available();
            return len;
        } catch (Exception e) {
			logger.log(Level.SEVERE, e.getMessage());
        }
        return -1;
    }

    /**
     * 将文件转化为base64
     *
     * @return
     * @throws Exception
     */
    public static String file2Base64(File inFile) {

        // 将文件转化为字节码
        byte[] bytes = copyFile2Byte(inFile);
        if (bytes == null) {
            return null;
        }

        // base64,将字节码转化为base64的字符串
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 将文件转化为字节码
     *
     * @param inFile
     * @return
     */
    private static byte[] copyFile2Byte(File inFile) {
        InputStream in = null;

        try {
            in = new FileInputStream(inFile);
            // 文件长度
            int len = in.available();

            // 定义数组
            byte[] bytes = new byte[len];

            // 读取到数组里面
            in.read(bytes);
            return bytes;
        } catch (Exception e) {
			logger.log(Level.SEVERE, e.getMessage());
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
				logger.log(Level.SEVERE, e.getMessage());
            }
        }
    }

    /**
     * 将字符串转化为文件
     *
     * @param strBase64 base64 编码的文件
     * @param outFile   输出的目标文件地址
     * @return
     */
    public static boolean base64ToFile(String strBase64, File outFile) {
        try {
            return copyByte2File(getBytes(strBase64), outFile);
        } catch (Exception e) {
			logger.log(Level.SEVERE, e.getMessage());
            return false;
        }
    }

    /**
     * 获取base64中的字节
     *
     * @param strBase64
     * @return
     */
    public static byte[] getBytes(String strBase64) {
        String[] split = strBase64.split(",");
        String faceBase64 = split.length == 2 ? split[1] : split[0];
        return Base64.getDecoder().decode(faceBase64);
    }

    /**
     * 获取文件后缀名
     *
     * @param strBase64
     * @return
     */
    public static String getFileSuffix(String strBase64) {
        String[] split = strBase64.split(",");
        if (split.length != 2) {
            return null;
        }
        String header = split[0];

        Matcher matcher = FILE_SUFFIX_PATTERN.matcher(header);
        return matcher.find() ? matcher.group(2) : null;
    }


    /**
     * 将字节码转化为文件
     *
     * @param bytes
     * @param file
     */
    private static boolean copyByte2File(byte[] bytes, File file) {
        FileOutputStream out = null;
        try {
            // 转化为输入流
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);

            // 写出文件
            byte[] buffer = new byte[1024];

            out = new FileOutputStream(file);

            // 写文件
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                // 文件写操作
                out.write(buffer, 0, len);
            }
            return true;
        } catch (Exception e) {

        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
				logger.log(Level.SEVERE, e.getMessage());
            }
        }
        return false;
    }

    protected static boolean isWhiteSpace(char octect) {
        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
    }

    protected static boolean isPad(char octect) {
        return (octect == PAD);
    }

    protected static boolean isData(char octect) {
        return (octect < BASE_LENGTH && BASE_64_ALPHABET[octect] != -1);
    }

    protected static boolean isBase64(char octect) {
        return (isWhiteSpace(octect) || isPad(octect) || isData(octect));
    }

    /**
     * Encodes hex octects into Base64
     *
     * @param binaryData Array containing binaryData
     * @return Encoded Base64 array
     */
    public static String encode(byte[] binaryData) {

        if (binaryData == null){
			return null;
		}
        int lengthDataBits = binaryData.length * BIT_EIGHT;
        if (lengthDataBits == 0) {
            return "";
        }

        int fewerThan24bits = lengthDataBits % TWENTY_FOUR_BIT_GROUP;
        int numberTriplets = lengthDataBits / TWENTY_FOUR_BIT_GROUP;
        int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
        char[] encodedData = null;

        encodedData = new char[numberQuartet * 4];

        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;

        int encodedIndex = 0;
        int dataIndex = 0;
        if (F_DEBUG) {
			logger.log(Level.FINER, "number of triplets = " + numberTriplets);
        }

        for (int i = 0; i < numberTriplets; i++) {
            b1 = binaryData[dataIndex++];
            b2 = binaryData[dataIndex++];
            b3 = binaryData[dataIndex++];

            if (F_DEBUG) {
				logger.log(Level.FINER, "b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
            }

            l = (byte)(b2 & 0x0f);
            k = (byte)(b1 & 0x03);

            byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0);

            byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0);
            byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc);

            if (F_DEBUG) {
                logger.log(Level.FINER, "val2 = " + val2);
                logger.log(Level.FINER, "k4   = " + (k << 4));
                logger.log(Level.FINER, "vak  = " + (val2 | (k << 4)));
            }

            encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[val1];
            encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[val2 | (k << 4)];
            encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[(l << 2) | val3];
            encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[b3 & 0x3f];
        }

        // form integral number of 6-bit groups
        if (fewerThan24bits == BIT_EIGHT) {
            b1 = binaryData[dataIndex];
            k = (byte)(b1 & 0x03);
            if (F_DEBUG) {
                logger.log(Level.FINER, "b1=" + b1);
                logger.log(Level.FINER, "b1<<2 = " + (b1 >> 2));
            }
            byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0);
            encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[val1];
            encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[k << 4];
            encodedData[encodedIndex++] = PAD;
            encodedData[encodedIndex++] = PAD;
        } else if (fewerThan24bits == BIT_SIXTEEN) {
            b1 = binaryData[dataIndex];
            b2 = binaryData[dataIndex + 1];
            l = (byte)(b2 & 0x0f);
            k = (byte)(b1 & 0x03);

            byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0);
            byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0);

            encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[val1];
            encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[val2 | (k << 4)];
            encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[l << 2];
            encodedData[encodedIndex++] = PAD;
        }

        return new String(encodedData);
    }

    /**
     * Decodes Base64 data into octects
     *
     * @param encoded string containing Base64 data
     * @return Array containind decoded data.
     */
    public static byte[] decode(String encoded) {

        if (encoded == null){
			return null;
		}
        char[] base64Data = encoded.toCharArray();
        // remove white spaces
        int len = removeWhiteSpace(base64Data);

        if (len % BYTE_FOUR != 0) {
			// should be divisible by four
            return null;
        }

        int numberQuadruple = (len / BYTE_FOUR);

        if (numberQuadruple == 0){
			return new byte[0];
		}
        byte[] decodedData = null;
        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
        char d1 = 0, d2 = 0, d3 = 0, d4 = 0;

        int i = 0;
        int encodedIndex = 0;
        int dataIndex = 0;
        decodedData = new byte[(numberQuadruple) * 3];

        for (; i < numberQuadruple - 1; i++) {

            if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
                    || !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))){
				// if
				return null;
			}
            // found
            // "no
            // data"
            // just
            // return
            // null
            b1 = BASE_64_ALPHABET[d1];
            b2 = BASE_64_ALPHABET[d2];
            b3 = BASE_64_ALPHABET[d3];
            b4 = BASE_64_ALPHABET[d4];

            decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4);
            decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
            decodedData[encodedIndex++] = (byte)(b3 << 6 | b4);
        }

        if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
			// if found "no data" just return null
            return null;
        }

        b1 = BASE_64_ALPHABET[d1];
        b2 = BASE_64_ALPHABET[d2];

        d3 = base64Data[dataIndex++];
        d4 = base64Data[dataIndex++];
		// Check if they are PAD characters
        if (!isData((d3)) || !isData((d4))) {
			// Two PAD e.g. 3c[Pad][Pad]
            if (isPad(d3) && isPad(d4)) {
                if ((b2 & 0xf) != 0) {
					return null;
                	// last 4 bits should be zero
				}
                byte[] tmp = new byte[i * 3 + 1];
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                tmp[encodedIndex] = (byte)(b1 << 2 | b2 >> 4);
                return tmp;
            } else if (!isPad(d3) && isPad(d4)) {
				// One PAD e.g. 3cQ[Pad]
                b3 = BASE_64_ALPHABET[d3];
                if ((b3 & 0x3) != 0){
					// last 2 bits should be zero
					return null;
				}
                byte[] tmp = new byte[i * 3 + 2];
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                tmp[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4);
                tmp[encodedIndex] = (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
                return tmp;
            } else {
				// an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
                return null;
            }
        } else {
			// No PAD e.g 3cQl
            b3 = BASE_64_ALPHABET[d3];
            b4 = BASE_64_ALPHABET[d4];
            decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4);
            decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
            decodedData[encodedIndex++] = (byte)(b3 << 6 | b4);

        }

        return decodedData;
    }

    /**
     * remove WhiteSpace from MIME containing encoded Base64 data.
     *
     * @param data the byte array of base64 data (with WS)
     * @return the new length
     */
    protected static int removeWhiteSpace(char[] data) {
        if (data == null){
			return 0;
		}
        // count characters that's not whitespace
        int newSize = 0;
        int len = data.length;
        for (int i = 0; i < len; i++) {
            if (!isWhiteSpace(data[i])){
				data[newSize++] = data[i];
			}
        }
        return newSize;
    }

}
